package dwz.cms.article.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import dwz.cms.article.util.ftp.FTPHost;
import dwz.cms.article.util.ftp.FTPUtils;
import dwz.cms.article.util.ftp.FtpError;
import dwz.cms.article.util.ftp.MyFTPFile;

/** 
* Created by Eclipse
* @author : Yating
* @version:2017年4月18日 上午9:13:47 
* 类说明 
*/
public class HtmlUtil {
	public static final String ROOT_URL = "http://localhost:8080/fcktest";
	public static Logger logger = Logger.getLogger(HtmlUtil.class.getName());
	public static int i = 0;

	public static String getHtmlContent(String url) {
		StringBuilder htmlSource = null;
		String linesep, htmlline;
		linesep = System.getProperty("line.separator");
		URL source;
		BufferedReader in = null;
		if (url.contains("?")) {
			url += "&pa=" + System.currentTimeMillis();
		} else {
			url += "?pa=" + System.currentTimeMillis();
		}

		try {
			htmlSource = new StringBuilder("");
			source = new URL(url);
			in = new BufferedReader(new InputStreamReader(source.openStream(),
					"UTF-8"));
			while ((htmlline = in.readLine()) != null) {
				htmlSource.append(htmlline).append(linesep);
			}
			logger.log(Level.INFO, "getHtmlContent:成功读取" + url);
		} catch (MalformedURLException e) {
			logger.log(Level.WARNING, "getHtmlContent:malformedURL", e);
		} catch (IOException e) {
			logger.log(Level.WARNING, "getHtmlContent:IOException", e);
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				logger.log(Level.WARNING,
						"getHtmlContent:closing reader error", e);
				e.printStackTrace();
			}
		}

		return htmlSource.toString();
	}

	public static String buildStaticSite(String indexURL, String goalPath) {
		String patternStr = "href=\".+.action.+\" ";
		Pattern pattern = Pattern.compile(patternStr);
		Matcher matcher = null;
		String source = null;
		String indexPage = ROOT_URL + "/" + indexURL;
		source = getHtmlContent(indexPage);
		matcher = pattern.matcher(source);

		while (matcher.find()) {
			String match = matcher.group();
			// source.substring(matcher.start(), matcher.end());
			match = match.replace("href=\"", "").replace("\" ", "");
			logger.log(Level.INFO, "buildStaticSite:匹配链接:" + match);
			source = source.replace(match, buildStaticSite(match, goalPath));
		}
		String name = generatePageName();
		writeToFile(source, new File(goalPath + name));
		logger.log(Level.INFO, "buildStaticSite:" + indexURL + "--->"
				+ goalPath + name);
		return name;
	}

	public static String buildStaticPage(String pageURL, String goalPath,
			String fileName) {
		String source = null;
		source = getHtmlContent(pageURL);
		if (goalPath.contains("contents"))
			source = coverPath(source); // 替换路径
		File basePath = new File(goalPath);

		if (!basePath.exists()) {
			basePath.mkdirs();
		}
		File baseFile = new File(basePath, fileName);
		writeToFile(source, baseFile);
		logger
				.log(Level.INFO, "buildStaticSite:" + pageURL + "--->"
						+ goalPath);
		return goalPath;
	}

	public static void writeToFile(String s, File file) {
		BufferedWriter fileWriter = null;
		try {
			fileWriter = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(file), "UTF-8"));
			fileWriter.write(s);
		} catch (IOException e) {
			logger.log(Level.WARNING, "writeToFile:IOException", e);
			e.printStackTrace();
		} finally {
			try {
				fileWriter.close();
			} catch (IOException e) {
				logger.log(Level.WARNING,
						"writeToFile:closing fileWriter error", e);
				e.printStackTrace();
			}
		}

	}

	public static String generatePageName() {
		Calendar calendar = Calendar.getInstance();
		String name = "" + calendar.HOUR + calendar.SECOND + i++;
		logger.log(Level.INFO, "generatePageName:生成文件名" + name);
		return name + Constants.EXT_HTM;

	}

	public static String generatePageName(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		String name = "" + calendar.HOUR + calendar.SECOND + i++;
		logger.log(Level.INFO, "generatePageName:生成文件名" + name);
		return name + Constants.EXT_HTM;

	}

	public static String generateFilePath(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return "" + new SimpleDateFormat("yyyy").format(date) + "/"
				+ new SimpleDateFormat("MM").format(date) + "/";
		// + new SimpleDateFormat("dd").format(date)+"\\";
	}

	/**
	 * 生成文章存储文件名,即code
	 * 
	 * @param date
	 * @return String 生成的code
	 */
	public static String generateCode(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		Format format = new SimpleDateFormat("yyMMddHHmmSSS");
		String s = format.format(calendar.getTime());
		return s;
	}

	/**
	 * 生成给定日期过期日期
	 * 
	 * @param date
	 *            原始日期
	 * @param field
	 *            年月日
	 * 
	 * @param duration
	 *            过期时长
	 * @return
	 */
	public static Date generateExpiryDate(Date date, int field, int duration) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(field, calendar.get(field) + duration);
		return calendar.getTime();
	}

	public static FtpError upLoadFiles(Vector<MyFTPFile> files) {
		FTPUtils ftp = new FTPUtils();
		FTPHost[] ftpHosts = Constants.JSEEA_STATIC_FTP_HOSTS;
		FtpError ftperror = ftp.upLoadFilesByThreads(ftpHosts, files);
		for (Iterator iterator = ftperror.getHashtable().keySet().iterator(); iterator
				.hasNext();) {
			Object hostName = (Object) iterator.next();
			String operation = ftperror.getMethodName().toUpperCase();
			String msg = (String) ftperror.getHashtable().get(hostName);
			logger.info(hostName + " :" + operation + ":::" + msg);
		}
		logger.info("Upload Finished");
		return ftperror;
	}

	public static String coverPath(String source) {
		String patternStr = "/\\w*?/Static/contents/channel_\\d+?/\\d+?/\\d+?/";
		// /\w*?/?Static/contents/channel_\d+?/\d+?/\d+?/
		return source.replaceAll(patternStr, "");

	}

	public static void main(String[] args) {
		String s = "<p>sdfsdfsdf<img alt=\"\" src=\"/EPORTAL/Static/contents/channel_4/2009/02/0902151633359.jpg\" /></p>"
				+ "<p>sdfsdfsdf<img alt=\"\" src=\"/EPORTAL/Static/contents/channel_4/2009/02/0902151633359.gif\" /></p>"
				+ "<p>sdfsdfsdf<img alt=\"\" src=\"/EPORTAL/Static/contents/channel_54/2009/1/0902151633359(334).doc\" /></p>";
		
		System.out.println(coverPath(s));
		
	}
	

}
 